package com.example.jones.test;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.util.CookbookImage;

public class HotAdepter extends BaseAdapter {

	// 定义需要包装的JSONArray对象
	private JSONArray jsonArray;
	ArrayList<HashMap<String, Object>> list;
    Handler hd;
    private Context ctx;
    
	public HotAdepter(Handler mhd,JSONArray jsonArray,Context ctx){
		this.jsonArray = jsonArray;
		this.ctx = ctx;
    	hd=mhd;
    }

	public int getCount() {
		return 5;
	}

	public Object getItem(int position) {
		return jsonArray.optJSONObject(position);
	}

	public long getItemId(int position) {
		try{
			// 返回物品的ID
			return ((JSONObject)getItem(position)).getInt("id");
		}
		catch (JSONException e){
			e.printStackTrace();
		}
		return 0;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		System.out.println("##################TopAdepter：getView");
		
		convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.hot_list_item, null);
	
		ImageView icon=(ImageView) convertView.findViewById(R.id.icon);
		TextView cbname=(TextView) convertView.findViewById(R.id.cbname);

		try {	
			CookbookImage cbimg=new CookbookImage();
			String dishImage=((JSONObject)getItem(position)).getString("dishImage");
			cbname.setText(((JSONObject)getItem(position)).getString("dishName"));
			icon.setImageBitmap(cbimg.getmybitmap(dishImage));
			
		} catch (JSONException e) {
			System.out.println("########HotAdepter：getView 获取JSONArray元素的属性出错！");
			e.printStackTrace();
		}

		icon.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent in=new Intent();
				try {
					in.putExtra("cbID", ((JSONObject)getItem(position)).getString("cookbookID"));
					in.putExtra("dishImage", ((JSONObject)getItem(position)).getString("dishImage"));
					in.putExtra("dishName", ((JSONObject)getItem(position)).getString("dishName"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
				in.setClass(ctx, DtlActivity.class);
				ctx.startActivity(in);
			}
		});
		
		return convertView;
	} 

}
